package kgc.crm.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import kgc.crm.dto.LeadsListDto;
import kgc.crm.enums.LabelTypeEnum;
import kgc.crm.mapper.CustomerMapper;
import kgc.crm.mapper.KgcCrmAdminFieldMapper;
import kgc.crm.model.Customer;
import kgc.crm.model.KgcCrmAdminField;
import kgc.crm.service.IActionRecordService;
import kgc.crm.service.ICustomerService;
import kgc.crm.util.EmptyChecker;
import kgc.crm.util.JWTManager;
import kgc.crm.util.ResultUtil;
import kgc.crm.vo.LeadsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;

@Service
@Slf4j
public class CustomerServiceImpl implements ICustomerService {
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private IActionRecordService recordService;
    @Autowired
    private KgcCrmAdminFieldMapper fieldMapper;

    @Override
    @Transactional
    public ResponseEntity add(Customer customer, String apiToken) {
        //判断customer是否为空
        if (EmptyChecker.isEmpty(customer)) {
            log.error("[用户模块] 添加失败，对象不能为空", customer);
            return ResultUtil.error("用户添加失败");
        }
        if (EmptyChecker.isEmpty(customer.getCustomerName())) {
            log.error("[用户模块] 添加失败，名字不能为空", customer);
            return ResultUtil.error("用户添加失败name");
        }
        Long id = JWTManager.getUserIDByToken(apiToken);
        customer.setBatchId(System.currentTimeMillis() + "");//设置批次id
        customer.setCreateUserId(id);//添加创建人id和负责人id
        customer.setOwnerUserId(id);
        //添加上次客户信息
        customer.setLastContent(JSON.toJSONString(customer));
        //执行新增操作
        int insert = -1;
        try {
            insert = customerMapper.insert(customer);
        } catch (Exception e) {
            log.error("[用户模块] 添加失败，sql语句执行错误", e);
            return ResultUtil.error("用户添加失败");
        }
        if (insert <= 0) {
            //添加失败，开启事务回归
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("[用户模块] 添加失败，sql语句执行错误", customer);
            return ResultUtil.error("添加失败");
        }
        //成功之后。添加操作记录
        //添加操作记录 构建ActionMapper
        if (!recordService.addActionRecord(id, customer.getCustomerId(), "新建了客户",LabelTypeEnum.CLIENT.getDesc())) {
            //如果是false
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
            return ResultUtil.error("客户添加失败");
        }
        return ResultUtil.success("客户添加成功");
    }

    @Override
    public ResponseEntity delete(Integer id) {
        if (EmptyChecker.isEmpty(id)) {
            log.error("[用户模块] 删除失败，参数不能为空");
            return ResultUtil.error("用户删除失败");
        }
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq(Customer.COL_CUSTOMER_ID, id);//客户id等于我们传进来的id
        int delete = -1;
        try {
            delete = customerMapper.deleteById(id);
        } catch (Exception e) {
            log.error("[用户模块] 删除失败，sql语句执行错误", e);
            return ResultUtil.error("用户删除失败");
        }
        if (delete <= 0) {
            log.error("[用户模块] 修改失败");
            return ResultUtil.error("用户删除失败");
        }
        return ResultUtil.success("成功删除用户");
    }

    @Override
    public ResponseEntity select(Integer id, String apiToken) {
        //根据id查找客户  判断是否是当前用户
        if (EmptyChecker.isEmpty(id)) {
            log.error("[用户模块] 查看失败，参数不能为空");
            return ResultUtil.error("查看用户失败");
        }
        Long token = JWTManager.getUserIDByToken(apiToken);
        System.out.println(token);
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq(Customer.COL_CREATE_USER_ID, token)
                .eq(Customer.COL_CUSTOMER_ID, id);
        List<Customer> list;
        try {
            list = customerMapper.selectList(wrapper);
        } catch (Exception e) {
            log.error("[用户模块] 查看失败，sql语句执行错误", e);
            return ResultUtil.error("查看用户失败");
        }
        if (EmptyChecker.isEmpty(list)) {
            log.error("[用户模块] 查看失败", list);
            return ResultUtil.error("查看用户失败");
        }
        return ResultUtil.success(list);
    }


    @Override
    public ResponseEntity update(Customer customer) {
        //判断customer是否为空
        if (EmptyChecker.isEmpty(customer)) {
            log.error("[用户模块] 修改失败，对象不能为空", customer);
            return ResultUtil.error("用户修改失败");
        }
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq(Customer.COL_CUSTOMER_ID, customer.getCustomerId());
        int update = -1;
        try {
            update = customerMapper.update(customer, wrapper);
        } catch (Exception e) {
            log.error("[用户模块] 修改失败，sql语句执行错误", e);
            return ResultUtil.error("用户修改失败");
        }
        if (update <= 0) {
            log.error("[用户模块] 修改失败", customer);
            return ResultUtil.error("用户修改失败");
        }
        return ResultUtil.success("用户修改成功");
    }



    @Override
    public ResponseEntity selectAll() {
//        if (EmptyChecker.isEmpty(customer)) {
//            log.error("[用户模块] 查看失败，参数不能为空");
//            return ResultUtil.error("查看用户失败");
//        }
        List<Customer> list = customerMapper.selectList(null);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param vo
     * @param apiToken
     * @return
     */
    @Override
    public ResponseEntity selectList(LeadsVo vo, String apiToken) {
        String fieldName = "";
        //当前登录的用户ID
        Long userId = JWTManager.getUserIDByToken(apiToken);
        if (!EmptyChecker.isEmpty(vo.getVo())) {
            KgcCrmAdminField field = fieldMapper.selectById(vo.getVo().getFieldId());
            fieldName = field.getFieldName();
        }
        LeadsListDto dto = new LeadsListDto(
                vo.getSearchVal()
                ,(vo.getPageIndex()-1) * vo.getPageSize()
                ,vo.getPageSize()
                ,vo.getVo()
                ,userId,fieldName
        );
        return ResultUtil.success(customerMapper.selectById(dto));
    }
}
